package top.zywork.weixin;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import top.zywork.common.HttpUtils;
import top.zywork.common.RedisUtils;
import top.zywork.enums.ClientAppEnum;

import java.util.concurrent.TimeUnit;

/**
 * 微信通用工具类<br/>
 *
 * 创建于2018-12-04<br/>
 *
 * @author 王振宇
 * @version 1.0
 */
@Slf4j
public class WeixinUtils {

    public static final String WEIXIN_ACCESS_TOKEN_KEY_IN_REDIS = "weixinAccessTokenKey";
    public static final int TOKEN_EXPIRES_MINUTES = 115;

    /**
     * 获取微信access_token，并存储到Redis缓存中，缓存时间为115分钟
     * @param redisTemplate
     * @param appId
     * @param appKey
     * @param clientAppEnum
     * @return
     */
    public static String getAccessToken(RedisTemplate<String, Object> redisTemplate, String appId, String appKey, ClientAppEnum clientAppEnum) {
        if (RedisUtils.exists(redisTemplate, WEIXIN_ACCESS_TOKEN_KEY_IN_REDIS)) {
            return RedisUtils.get(redisTemplate, WEIXIN_ACCESS_TOKEN_KEY_IN_REDIS).toString();
        }
        String accessTokenApi = "";
        if (clientAppEnum.getValue().equals(ClientAppEnum.WEIXIN_GZH.getValue())) {
            accessTokenApi = GzhConstants.ACCESS_TOKEN_URL;
        } else if (clientAppEnum.getValue().equals(ClientAppEnum.WEIXIN_XCX.getValue())){
            accessTokenApi = XcxConstants.ACCESS_TOKEN_URL;
        }
        String response = HttpUtils.get(accessTokenApi.replace("{APP_ID}", appId).replace("{APP_KEY}", appKey));
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (!response.contains(WeixinConstants.ERROR_CODE_STR)) {
            String accessToken = jsonObject.get("access_token").toString();
            RedisUtils.save(redisTemplate, WEIXIN_ACCESS_TOKEN_KEY_IN_REDIS, accessToken, TOKEN_EXPIRES_MINUTES, TimeUnit.MINUTES);
            return accessToken;
        }
        log.error("get access token error: {}", errmsg(jsonObject));
        return null;
    }

    public static boolean isResultOk(JSONObject resultJsonResult) {
        Object errcode = resultJsonResult.get(WeixinConstants.ERROR_CODE_STR);
        return  errcode != null && Integer.parseInt(errcode.toString()) == 0;
    }

    public static String errmsg(JSONObject resultJsonResult) {
        return resultJsonResult.get(WeixinConstants.ERROR_MSG_STR).toString();
    }

}
